<template>
<div>
  <h1>Card from Contacts</h1>
  <div v-if="fingerprint">
    <p>{{fingerprint}}</p>
    <div v-for="(card, index) in contactsCards" v-bind:key="index">
      <div v-if="card.fingerprint.replace(/[: ]/gi,'') === fingerprint.replace(/[: ]/gi,'')">
        <BusinessCard :card="card"/>
        <TextEncrypter :rsaPubKey="getPubKey(fingerprint)"/>
        <p>
          <pre>{{JSON.stringify(card, null, 1)}}</pre>
        </p>
        <p><button v-on:click="toggleLock()">Click to toggle lock</button></p>
        <div v-if="!locked">
          <p><strong>WARNING&#58;</strong>
            This will remove the card if you click the button below.</p>
          <button v-on:click="rmCard(index)" class="danger">Remove Card</button>
        </div>
      </div>
    </div>
  </div>
  <div v-else>
    <p>No fingerprint.</p>
  </div>
</div>
</template>

<script>
import {mapState, mapGetters, mapMutations, mapActions} from "vuex"
import BusinessCard from '@/components/BusinessCard.vue'
import TextEncrypter from '@/components/TextEncrypter.vue'

export default {
    name: "Card",
    components: {
        BusinessCard,
        TextEncrypter
    },
    data() {
        return {
            locked: true
        }
    },
    props: ["fingerprint"],
    computed: {
        ...mapState([
            "contactsCards"
        ]),
        ...mapGetters([
            "getCardFromFingerprint"
        ])
    },
    methods: {
        ...mapGetters({
            keyPair: "getKeyFromFingerprint"
        }),
        ...mapMutations([
            "rmContactsCard",
        ]),
        ...mapActions({
            rmCard: "rmCard",
        }),
        getPubKey: function(fingerprint) {
            const keyPairs = this.keyPair()(fingerprint)
            return (keyPairs.length > 0) ? keyPairs[0].pubKey : undefined
        },
        toggleLock: function() {
            this.locked = !this.locked
        },
        getAvatar: function(email) {
            let hexval = this.getHash(email);
            return `https://www.libravatar.org/avatar/${hexval}?s=80`;
        },
        getHash: function(text) {
            try {
                const crypto = require('crypto');
                const hash = crypto.createHash('sha256')
                      .update(text)
                      .digest('hex');
                return hash;
            } catch (err) {
                console.log('crypto support is disabled!');
            }
        }
    }
}
</script>

<style scoped>
</style>
